package com.qf.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author:huayuzhuo
 * @email:2798866329@qq.com
 * @desc:封装工具类，连接数据库方法类
 * @datetime 2022/5/24 10:13
 */
public class DBUtils {
    //druid的数据源
    private static DruidDataSource ds;
    private static  final ThreadLocal<Connection>THREAD_LOCAL = new ThreadLocal<> ();

    static {
        //加载配置文件对象
        Properties properties=new Properties (  );
        try {
            properties.load(new FileInputStream("E:\\IdeaProjects\\Hospiatl_huayuzhuo\\database.properties"));
            //强转类型      通过工厂加载数据源
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource (properties);
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
    //数据连接
    public  static  Connection getConnection(){
        Connection connection = THREAD_LOCAL.get ();
        try {
            connection = ds.getConnection ();
            THREAD_LOCAL.set (connection);
        } catch (SQLException e) {
            e.printStackTrace ();
        }
        return  connection;
    }
    //事务的开启
    public static void begin(){
        Connection connection =null;
        try {
            connection=getConnection ();
            //手动开启事务
            connection.setAutoCommit ( false );
        } catch (SQLException e) {
            e.printStackTrace ();
        }
    }
    //提交事务
    public  static  void commit(){
        Connection connection =null;
        try {
            connection=getConnection ();
            connection.commit ();
        } catch (SQLException e) {
            e.printStackTrace ();
        }finally {
            closeAll ( connection,null,null );
        }
    }
    //事务的回滚
    public static  void rollback(){
        Connection connection=null;
        connection=getConnection ();
        try {
            connection.rollback ();
        } catch (SQLException e) {
            e.printStackTrace ();
        }finally {
            closeAll ( connection,null,null );
        }
    }
    //释放资源
    public static  void  closeAll(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if (resultSet !=null){
                resultSet.close ();
            }
            if (statement !=null){
                statement.close ();
            }
            if (connection !=null){
                connection.close ();
            }
        } catch (SQLException e) {
            e.printStackTrace ();
        }
    }

    public static DataSource getDataSource(){
        return ds;
    }
}
